package com.qingneng.budget.util;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.aopalliance.intercept.Invocation;

import net.sf.json.JSONObject;

import com.lowagie.text.pdf.crypto.IVGenerator;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class JSONParamReadIntercepter extends AbstractInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String jsonParamData = "jsonRequestParamter";

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext ctx = ActionContext.getContext();
		Map<String, Object> requestParam = ctx.getParameters();
		boolean excuteFlag = false;
		if (requestParam != null) {

			String[] jsonParamObj = (String[]) requestParam.get(jsonParamData);

			if (jsonParamObj != null && jsonParamObj.length > 0) {

				String jsonParamObjStr = (String) (jsonParamObj[0]);

				requestParam = this.json2Map(jsonParamObjStr, requestParam,
						null, null);

				if (requestParam != null && requestParam.size() > 0) {
					excuteFlag = true;

					for (Object key : requestParam.keySet()) {
						System.out.print("key:" + key);
						System.out.print("  value:" + requestParam.get(key));
					}
				}
			}
		}
		if (!excuteFlag) {
			System.out
					.println(" NO JSON Paramter or JSON paramter's name have error ");
		}
		return invocation.invoke();

	}

	public Map<String, Object> json2Map(String jsonObjectStr,
			Map<String, Object> map, String[] excludes, String datePattern)
			throws Exception {
		JSONObject jsonObject = JSONObject.fromObject(jsonObjectStr);
		Set<String> excludeSet = createExcludeSet(excludes);
		for (Object object : jsonObject.entrySet()) {
			Map.Entry entry = (Map.Entry) object;
			String propertyName = entry.getKey().toString();

			if (excludeSet.contains(propertyName)) {
				continue;
			}

			String propertyValue = entry.getValue().toString();
			map.put(propertyName, propertyValue);
		}

		return map;

	}

	public Set<String> createExcludeSet(String[] excludes) {
		Set<String> excludeSet = new HashSet<String>();
		if (excludes != null && excludes.length > 0) {
			for (int i = 0; i < excludes.length; i++) {
				excludeSet.add(excludes[0]);
			}
		}
		return excludeSet;

	}

}
